package online.yysh.charging.fragment;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.BitmapFactory;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatDialog;
import androidx.core.app.ActivityCompat;

import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;

import com.amap.api.maps.LocationSource;
import com.amap.api.maps.TextureMapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeAddress;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.google.gson.Gson;
import online.yysh.charging.ChargingActivity;
import online.yysh.charging.MyPreChargeActivity;
import online.yysh.charging.R;
import online.yysh.charging.ScanAndChargeActivity;
import online.yysh.charging.SubscribeActivity;
import online.yysh.charging.VagueQueryActivity;
import online.yysh.charging.base.BaseFragment;
import online.yysh.charging.bean.ChargingPile;
import online.yysh.charging.bean.Login;
import online.yysh.charging.bean.User;
import online.yysh.charging.bean.request.GetAllStationsRequest;
import online.yysh.charging.bean.response.GetAuthMsgResponse;
import online.yysh.charging.bean.response.GetDeatailPortInfoResponse;
import online.yysh.charging.bean.response.GetStationsResponse;
import online.yysh.charging.bean.response.Station;
import online.yysh.charging.livedata.AddressManager;
import online.yysh.charging.livedata.BindPhoneManager;
import online.yysh.charging.livedata.UserManager;
import online.yysh.charging.utils.HttpUtil;
import online.yysh.charging.utils.ToastUtil;

import java.io.IOException;
import java.io.Serializable;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * 地图
 */
public class MapViewFragment extends BaseFragment implements AMap.OnMarkerClickListener, View.OnClickListener, LocationSource, AMapLocationListener, GeocodeSearch.OnGeocodeSearchListener {

    // 高德地图包名
    public static final String PN_GAODE_MAP = "com.autonavi.minimap";
    //地理编码
    GeocodeSearch geocoderSearch;

    private AMap aMap;
    private TextureMapView textureMapView;
    //状态栏
    private LinearLayout ll_status;
    //扫码充电按钮
    private Button btn_scan;
    //当前状态（预约充电、正在充电）
    private TextView tv_status;
    //模糊查询
    private ImageView iv_search;

    //定位需要的数据
    private LocationSource.OnLocationChangedListener listener;
    private AMapLocationClient locationClient;
    private AMapLocationClientOption locationClientOption;
    private MyLocationStyle myLocationStyle;

    //位置权限
    private String locationPermissions = Manifest.permission.ACCESS_FINE_LOCATION;

    //Marker与电站Map
    private Map<String, Station> markerChargingMap = new HashMap<>();

    //定位成功
    private static final int LOCATION_SUCCEED = 200;
    //定位失败
    private static final int LOCATION_FAILED = 201;
    //查询电站信息成功
    private static final int QUERY_SUCCEED = 400;
    //查询电站信息失败
    private static final int QUERY_FAILED = 401;
    //位置权限请求code
    private static final int LOCATION_REQUEST_CODE = 300;
    //打开GPS请求
    private static final int OPEN_GPS = 301;
    //根据ID查询电站信息成功
    private static final int DIALOG_SUCCEED = 500;
    //查询用户状态信息成功
    private static final int QUERY_USER_SUCCEED = 600;
    //查询用户状态信息失败
    private static final int QUERY_USER_FAILED = 601;
    //循环查询用户状态
    private static final int WHILE_TRUE_QUERY = 700;

    private User user;

    //当前纬度
    private double myLat;
    //当前经度
    private double myLon;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what) {
                case LOCATION_SUCCEED:
                    String location = (String) msg.obj;
                    String[] locationArr = location.split("-");
                    GetAllStationsRequest request = new GetAllStationsRequest(locationArr[1],locationArr[0],"");
                    getAllStations(request);
                    break;
                case LOCATION_FAILED:

                    break;
                case QUERY_SUCCEED:
                    //查询成功，在地图上画出电站
                    GetStationsResponse response = (GetStationsResponse) msg.obj;
                    if (response != null) {
                        List<Station> stationList = response.getData();
                        for (Station station : stationList) {
                            LatLng latLng = new LatLng(Double.valueOf(station.getLatitude()), Double.valueOf(station.getLongtitude()));
                            markerChargingMap.put(addMarkersToMap(latLng, station.getName()).getId(), station);
                        }
                    }
                    break;
                case QUERY_FAILED:

                    break;
                case DIALOG_SUCCEED:
                    Station station = (Station) msg.obj;
                    showDialog(station);
                    break;
                case QUERY_USER_SUCCEED:
                    //获取绑定的手机号
                    final String phoneNumber = user.getPhone_number();
                    if (!TextUtils.isEmpty(phoneNumber)) {
                        BindPhoneManager.getInstance().getLiveData().setValue(phoneNumber);
                    }
                    UserManager.getInstance().getLiveData().setValue(new Login().setMoney(user.getMoney()).setOpenid(user.getUserID()));

                    //用户当前状态
                    int status = user.getStatus();
                    if (status == 8) {
                        //用户预约了充电
                        ll_status.setVisibility(View.VISIBLE);
                        tv_status.setText("预约充电");
                    } else if (status == 3) {
                        //用户正在充电
                        ll_status.setVisibility(View.VISIBLE);
                        tv_status.setText("正在充电");
                    } else {
                        ll_status.setVisibility(View.INVISIBLE);
                    }
                    break;
                case QUERY_USER_FAILED:
                    //查询用户状态信息失败
                    ll_status.setVisibility(View.INVISIBLE);
                    break;
                case WHILE_TRUE_QUERY:
                    //检测当前充电状态
                    checkChargingStatus();
                    handler.sendEmptyMessageDelayed(WHILE_TRUE_QUERY, 1000 * 30);
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    public View initView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_map_view, null);
        iv_search = view.findViewById(R.id.iv_search);
        iv_search.setOnClickListener(this);
        ll_status = view.findViewById(R.id.ll_status);
        ll_status.setOnClickListener(this);
        tv_status = view.findViewById(R.id.tv_status);
        textureMapView = view.findViewById(R.id.tmv);
        textureMapView.onCreate(savedInstanceState);
        btn_scan = view.findViewById(R.id.btn_scan);
        btn_scan.setOnClickListener(this);
        return view;
    }

    /**
     * 初始化高德地图
     */
    public void initMap() {
        geocoderSearch = new GeocodeSearch(getActivity());
        geocoderSearch.setOnGeocodeSearchListener(this);

        aMap = textureMapView.getMap();
        /**
         * 一定要先设置定位监听，否则首次进入该页面时不会自动定位并显示当前位置
         */
        aMap.setLocationSource(this);
        // 如果要设置定位的默认状态，可以在此处进行设置
        myLocationStyle = new MyLocationStyle();
        //设置连续定位模式下定位时间间隔
        myLocationStyle.interval(2000);
        //连续定位、且将视角移动到地图中心
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATE);
        myLocationStyle.showMyLocation(true);
        //设置蓝点style
        aMap.setMyLocationStyle(myLocationStyle);
        //控件交互
        UiSettings uiSettings = aMap.getUiSettings();
        //显示指南针
        uiSettings.setCompassEnabled(true);
        //关闭显示缩放按钮
        uiSettings.setZoomControlsEnabled(false);
        // 设置默认定位按钮是否显示
        uiSettings.setMyLocationButtonEnabled(true);
        // 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
        aMap.setMyLocationEnabled(true);
        //设置Maker点击监听
        aMap.setOnMarkerClickListener(this);
    }

    /**
     * 查询周围所有枪
     *
     * @param getRoundPortRequest
     */
//    public void getRoundPort(GetRoundPortRequest getRoundPortRequest) {
//        HttpUtil.getInstance().getRoundPort(getRoundPortRequest, new Callback() {
//            @Override
//            public void onFailure(Call call, IOException e) {
//                e.printStackTrace();
//                Message message = Message.obtain();
//                message.what = QUERY_FAILED;
//            }
//
//            @Override
//            public void onResponse(Call call, Response response) throws IOException {
//                String result = response.body().string();
//                Log.e(TAG, "result:" + result);
//                Gson gson = new Gson();
//                GetRoundPortResponse resultBean = gson.fromJson(result, GetRoundPortResponse.class);
//                Message message = Message.obtain();
//                message.obj = resultBean;
//                message.what = QUERY_SUCCEED;
//                handler.sendMessage(message);
//            }
//        });
//    }


    /**
     * 获取所有电站
     * @param request
     */
    public void getAllStations(GetAllStationsRequest request){
        HttpUtil.getInstance().getStations(request, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
                Message message = Message.obtain();
                message.what = QUERY_FAILED;
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                Log.e(TAG, "getAllStations:" + result);
                Gson gson = new Gson();
                GetStationsResponse getStationsResponse = gson.fromJson(result, GetStationsResponse.class);
                Message message = Message.obtain();
                message.obj = getStationsResponse;
                message.what = QUERY_SUCCEED;
                handler.sendMessage(message);
            }
        });
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        //初始化地图
        initMap();
        //验证权限
        requestPermission();
        handler.sendEmptyMessage(WHILE_TRUE_QUERY);
    }

    /**
     * 检测当前账户充电状态
     */
    private void checkChargingStatus() {
        if (!TextUtils.isEmpty(openid)) {
            HttpUtil.getInstance().getAuthMsg(openid, new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    e.printStackTrace();
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String result = response.body().string();
                    Log.e(TAG, "getAuthMsg: " + result);
                    GetAuthMsgResponse data = new Gson().fromJson(result, GetAuthMsgResponse.class);
                    if ("ok".equals(data.getStatus())) {
                        user = data.getData();
                        handler.sendEmptyMessage(QUERY_USER_SUCCEED);
                    } else {
                        //获取信息失败
                        handler.sendEmptyMessage(QUERY_USER_FAILED);
                    }
                }
            });
        }
    }

    /**
     * 申请权限
     */
    public void requestPermission() {
        //申请定位权限
        if (PackageManager.PERMISSION_GRANTED == ActivityCompat.checkSelfPermission(getActivity(), locationPermissions)) {
            if (!isOPen()) {
                showOpenGPSDialog();
            }
        } else {
            requestPermissions(new String[]{locationPermissions}, LOCATION_REQUEST_CODE);
        }
    }

    /**
     * 权限申请结果回调
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (grantResults.length > 0) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                if (!isOPen()) {
                    showOpenGPSDialog();
                }
            } else {
                //授权失败
                ToastUtil.showToast(getActivity(), R.string.prompt_location_permission);
            }
        }
    }

    /**
     * 检测GPS是否开启
     *
     * @return
     */
    public boolean isOPen() {
        LocationManager locationManager
                = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
        // 通过GPS卫星定位，定位级别可以精确到街（通过24颗卫星定位，在室外和空旷的地方定位准确、速度快）
        boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        // 通过WLAN或移动网络(3G/2G)确定的位置（也称作AGPS，辅助GPS定位。主要用于在室内或遮盖物（建筑群或茂密的深林等）密集的地方定位）
        boolean network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        if (gps || network) {
            return true;
        }

        return false;
    }

    @Override
    public void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        textureMapView.onSaveInstanceState(outState);
    }

    @Override
    public void onResume() {
        super.onResume();
        textureMapView.onResume();
        checkChargingStatus();
    }

    @Override
    public void onPause() {
        super.onPause();
        textureMapView.onPause();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        textureMapView.onDestroy();
        if (locationClient != null) {
            locationClient.onDestroy();
        }
    }

    /**
     * 在地图上添加marker
     */
    private Marker addMarkersToMap(LatLng latLng, String title) {
        MarkerOptions markerOption = new MarkerOptions().icon(BitmapDescriptorFactory
                .defaultMarker(BitmapDescriptorFactory.HUE_BLUE))
                .position(latLng)
//                .title(title)
                .draggable(true)
                .icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                        .decodeResource(getResources(),
                                R.mipmap.marker)));
        Marker marker = aMap.addMarker(markerOption);
        marker.showInfoWindow();
        return marker;
    }

    @Override
    public boolean onMarkerClick(Marker marker) {
        //每次点击Marker都需要请求一次电站数据
        Station station = markerChargingMap.get(marker.getId());
        if (station != null) {
            //根据电站ID请求数据
//            requestStationAddress(new LatLonPoint(Double.valueOf(station.getLatitude()),Double.valueOf(station.getLongtitude())));
            getStationInfo(station);
        }
        return true;
    }

    /**
     * 根据电站编号获取电站信息
     *
     * @param chargingBean
     */
    private void getStationInfo(final Station station) {
        HttpUtil.getInstance().getDeatailPortInfo(station.getID() + "", new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                Log.e(TAG, "getDeatailPortInfo: " + result);
                Gson gson = new Gson();
                GetDeatailPortInfoResponse dataResponse = gson.fromJson(result, GetDeatailPortInfoResponse.class);
                if ("ok".equals(dataResponse.getStatus())) {
                    List<ChargingPile> piles = dataResponse.getData();
                    station.setKXPortCount(piles.size());
                    Message message = Message.obtain();
                    message.obj = station;
                    message.what = DIALOG_SUCCEED;
                    handler.sendMessage(message);
                } else {
                    showToast(getResources().getString(R.string.query_station_error));
                }
            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_scan:
                startActivity(new Intent(getActivity(), ScanAndChargeActivity.class));

//                StopChargingRequest request = new StopChargingRequest(WXConstant.WX_UNION_ID,1,"");
//                HttpUtil.getInstance().stopCharge(request, new Callback() {
//                    @Override
//                    public void onFailure(Call call, IOException e) {
//                        e.printStackTrace();
//                    }
//
//                    @Override
//                    public void onResponse(Call call, Response response) throws IOException {
//                        String result = response.body().string();
//                        Log.e(TAG, "stopCharge:"+result );
//                    }
//                });
                break;
            case R.id.ll_status:
                if (user.getStatus() == 3) {
                    //跳转至正在充电页面
                    Intent intent = new Intent(getActivity(), ChargingActivity.class);
                    intent.putExtra("User", (Serializable) user);
                    startActivity(intent);
                } else if (user.getStatus() == 8) {
                    //跳转至预约页面
                    Intent intent = new Intent(getActivity(), MyPreChargeActivity.class);
                    startActivity(intent);
                }
                break;
            case R.id.iv_search:
                Intent intent = new Intent(getActivity(), VagueQueryActivity.class);
                intent.putExtra("data",myLon+"_"+myLat);
                startActivity(intent);
                break;
        }
    }

    /**
     * 底部弹窗
     */
    public void showDialog(final Station  station) {
        AppCompatDialog appCompatDialog = new AppCompatDialog(getActivity());
        View view = getLayoutInflater().inflate(R.layout.dialog_station_info, null);
        //显示距离
        TextView tv_distance = view.findViewById(R.id.tv_distance);
        //电站名称
        TextView tv_stationName = view.findViewById(R.id.tv_stationName);
        //总枪数
        TextView tv_gunsCount = view.findViewById(R.id.tv_gunsCount);
        //可用枪数
        TextView tv_availableCount = view.findViewById(R.id.tv_availableCount);
        //具体位置
        TextView tv_location = view.findViewById(R.id.tv_location);
        tv_location.setText(station.getAddress());
//        AddressManager.getInstance().getLiveData().observe(getActivity(), new Observer<String>() {
//            @Override
//            public void onChanged(String s) {
//                tv_location.setText(s);
//            }
//        });
        //导航按钮
        ImageView iv_navigation = view.findViewById(R.id.iv_navigation);
        iv_navigation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openGaoDeNavi(getActivity(), myLat, myLon, "我的位置", Double.valueOf(station.getLatitude()), Double.valueOf(station.getLongtitude()), station.getName());
            }
        });
        tv_availableCount.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (station.getKXPortCount() > 0) {
                    goSubscribe(station);
                }
            }
        });
        tv_stationName.setText(station.getName());
        BigDecimal bigDecimal = new BigDecimal(station.getDistance());
        float distance = bigDecimal.setScale(2, RoundingMode.HALF_UP).floatValue();
        tv_distance.setText(distance + "km");
        tv_gunsCount.setText(getResources().getString(R.string.device_count) + station.getPortCount());
        tv_availableCount.setText(getResources().getString(R.string.useful_count) + station.getKXPortCount());
        appCompatDialog.setContentView(view);
        Window window = appCompatDialog.getWindow();
        window.setGravity(Gravity.BOTTOM);
        //设置一个透明背景，不然会显示不全
        window.setBackgroundDrawableResource(R.color.transparent);
        window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        appCompatDialog.show();
    }

    /**
     * 进入预约页面
     *
     * @param station
     */
    private void goSubscribe(Station station) {

        Intent intent = new Intent(getActivity(), SubscribeActivity.class);
        intent.putExtra("chargingBean", station);
        startActivity(intent);
    }

    /**
     * 打开GPS
     */
    public void openGPS() {
        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
        startActivityForResult(intent, OPEN_GPS);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (requestCode == OPEN_GPS) {
            //再判断一次gps是否打开，如果打开则加载地图
            if (isOPen()) {
                initMap();
            } else {
                Toast.makeText(getActivity(), R.string.prompt_gps_failed, Toast.LENGTH_SHORT).show();
            }
        }
    }

    /**
     * 打开GPS对话框
     */
    public void showOpenGPSDialog() {
        final AppCompatDialog appCompatDialog = new AppCompatDialog(getActivity());
        appCompatDialog.setCancelable(false);
        View view = getLayoutInflater().inflate(R.layout.dialog_open_gps, null);
        TextView tv_cancel = view.findViewById(R.id.tv_cancel);
        tv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ToastUtil.showToast(getActivity(), R.string.prompt_gps_failed);
                appCompatDialog.dismiss();
            }
        });
        TextView tv_confirm = view.findViewById(R.id.tv_confirm);
        tv_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                appCompatDialog.dismiss();
                openGPS();
            }
        });
        appCompatDialog.setContentView(view);
        Window window = appCompatDialog.getWindow();
        window.setBackgroundDrawableResource(R.color.transparent);
        window.setGravity(Gravity.CENTER);
        window.setLayout(800, ViewGroup.LayoutParams.WRAP_CONTENT);
        appCompatDialog.show();
    }

    /**
     * 打开高德地图导航功能
     *
     * @param context
     * @param slat    起点纬度
     * @param slon    起点经度
     * @param sname   起点名称 可不填（0,0，null）
     * @param dlat    终点纬度
     * @param dlon    终点经度
     * @param dname   终点名称 必填
     */
    public void openGaoDeNavi(Context context, double slat, double slon, String sname, double dlat, double dlon, String dname) {
        String uriString = null;
        StringBuilder builder = new StringBuilder("amapuri://route/plan?sourceApplication=maxuslife");
        if (slat != 0) {
            builder.append("&sname=").append(sname)
                    .append("&slat=").append(slat)
                    .append("&slon=").append(slon);
        }
        builder.append("&dlat=").append(dlat)
                .append("&dlon=").append(dlon)
                .append("&dname=").append(dname)
                .append("&dev=0")
                .append("&t=0");
        uriString = builder.toString();
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setPackage(PN_GAODE_MAP);
        intent.setData(Uri.parse(uriString));
        context.startActivity(intent);
    }

    /**
     * 启动定位
     *
     * @param onLocationChangedListener
     */
    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {
        listener = onLocationChangedListener;
        if (locationClient == null) {
            //初始化定位
            locationClient = new AMapLocationClient(getActivity());
            //初始化定位参数
            locationClientOption = new AMapLocationClientOption();
            //设置定位回调监听
            locationClient.setLocationListener(this);
            //设置为高精度定位模式
            locationClientOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            //设置定位参数
            locationClient.setLocationOption(locationClientOption);
            // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
            // 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
            // 在定位结束后，在合适的生命周期调用onDestroy()方法
            // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
            //启动定位
            locationClient.startLocation();
        }
    }

    /**
     * 停止定位
     */
    @Override
    public void deactivate() {
        listener = null;
        if (locationClient != null) {
            locationClient.startLocation();
            locationClient.onDestroy();
        }
        locationClient = null;
    }
                                                            private int firstLocation;

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (listener != null && aMapLocation != null) {
            if (aMapLocation.getErrorCode() == 0) {
                //显示系统小蓝点
                listener.onLocationChanged(aMapLocation);
                myLat = aMapLocation.getLatitude();
                myLon = aMapLocation.getLongitude();
//                Log.e(TAG, "定位成功， lat: " + myLat + " lon: " + myLon);
                if (firstLocation == 0) {
                    Message message = Message.obtain();
                    message.what = LOCATION_SUCCEED;
                    message.obj = aMapLocation.getLatitude() + "-" + aMapLocation.getLongitude();
                    handler.sendMessage(message);
                    firstLocation++;
                }
            } else {
//                Log.e(TAG, "定位失败," + aMapLocation.getErrorCode() + ": " + aMapLocation.getErrorInfo());
                handler.sendEmptyMessage(LOCATION_FAILED);
            }
        }
    }

    private void requestStationAddress(LatLonPoint latLonPoint){
        // 第一个参数表示一个Latlng，第二参数表示范围多少米，第三个参数表示是火系坐标系还是GPS原生坐标系
        RegeocodeQuery query = new RegeocodeQuery(latLonPoint, 50,GeocodeSearch.AMAP);
        geocoderSearch.getFromLocationAsyn(query);
    }

    private String stationAddress = "";

    //逆地理编码
    @Override
    public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int i) {
        RegeocodeAddress address = regeocodeResult.getRegeocodeAddress();
        stationAddress = address.getFormatAddress();
        AddressManager.getInstance().getLiveData().setValue(stationAddress);
        Log.e(TAG,"onRegeocodeSearched:"+stationAddress);
    }

    @Override
    public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {

    }
}